package com.zky.gulimall.order.listener;

import com.rabbitmq.client.Channel;
import com.zky.common.to.mq.SecKillOrderTo;
import com.zky.gulimall.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Description 秒杀单监听
 * @Author 张开源
 * @Date 2023/1/6 17:42
 * @Version 1.0
 **/
@Component
@RabbitListener(queues = "order.seckill.order.queue")
@Slf4j
public class OrderSecKillListener {
    @Autowired
    private OrderService orderService;

    private static int retryCount = 0;

    /**
     * 手动确认,失败重试需要接受到异常信息,如果必须要try catch 操作,需要在catch里，把异常抛出去，ack拒绝重新入队不能解决无限重试问题。
     *
     * @param secKillOrderTo
     * @param channel
     * @param message
     * @throws IOException
     */
    @RabbitHandler
    public void secKillOrderListener(SecKillOrderTo secKillOrderTo, Channel channel, Message message) throws IOException {
        try {
            log.warn("收到秒杀订单信息，订单信息：{}", secKillOrderTo);
            //有订单状态，能防止消息重复投递
            orderService.createSecKillOrder(secKillOrderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            retryCount=0;
            log.warn("secKillOrderListener 手动确认消息完毕------------------------------------ack 确认");
        } catch (IOException e) {
            log.error("收到秒杀订单信息，准备创建秒杀订单，创建出现异常,secKillOrderTo：{},e:", secKillOrderTo, e.getLocalizedMessage());
            if (retryCount >= 3) {
                //记录消息数据表，后续补偿拒绝不再入队
                retryCount = 0;
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
                return;
            }
            retryCount++;
            throw new RuntimeException("收到秒杀订单信息，准备创建秒杀订单，创建出现异常,msg:" + e.getLocalizedMessage());
        }

    }
}
